package com.doerit.action.signin;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.doerit.action.index.IndexAction;
import com.doerit.exception.SessionNotExist;
import com.doerit.model.User;
import com.doerit.service.impl.EmailService;
import com.doerit.service.impl.UserServiceImpl;
import com.doerit.util.EmailUtil;
import com.doerit.util.SessionKey;

public class SignInAction extends IndexAction {

  private static final long serialVersionUID = 1L;
  private static Logger logger = Logger.getLogger(SignInAction.class);

  private User user;

  @Autowired
  private UserServiceImpl userServiceImpl;
  @Autowired
  private EmailService emailService;

  public String signIn() {

    try {
      user = userServiceImpl.findByNameAndPassword(user.getEmail(), user.getPassword());
      System.out.println(user.getName());
      try {
        addSessionStaffVariable(user);
        status = STATUS.SUCCESS;
        return SUCCESS;
      } catch (SessionNotExist e) {
        logger.error("[User] session variable set exception");
        addActionError(getText("user.login.error.authentication"));
        status = STATUS.FAILURE;
        return INPUT;
      }

    } catch (Exception e) {
      logger.error(e.getMessage());
    }

    return INPUT;
  }

  public String signOut() {

    try {
      removeSessionVariable(SessionKey.SESSION_USER);
      removeSessionVariable(SessionKey.RESPONSE);
      removeSessionVariable(SessionKey.HISTORY_ACTION);
    } catch (SessionNotExist e) {
      logger.error(e);
    }

    return SUCCESS;
  }

  public String requestForgetPassword() {

    String emailAddress = user.getEmail();
    if (emailAddress != null && !emailAddress.isEmpty()) {

      if (EmailUtil.chackEmailPattern(emailAddress)) {

        String key = emailService.sendEmail(emailAddress);
        addActionError(getText(key));

        if (key.startsWith("error")) {
          addActionError(getText("error.email.invalid"));
          return INPUT;
        } else {
          return SUCCESS;
        }

      } else {
        addActionError(getText("error.email.invalid"));
        return INPUT;
      }

    } else {
      addActionError(getText("error.email.empty"));
      return INPUT;
    }
  }

  public String forgotPassword() {
    return SUCCESS;
  }

  public STATUS getStatus() {
    return status;
  }

  public User getUser() {
    return user;
  }

  public void setUser(User user) {
    this.user = user;
  }



}
